'''
# -*- coding:utf-8 -*-
# @Project: DevOps_api
# @Date: 2023/3/16 - 21:16
# @Author: ysg
# @Describe: 

ops_task.py
'''

from django.core.cache import cache
from celery_task.celery import app
from libs.connect_ssh.devops_ssh import do_ssh
from libs.connect_influxdb.Ops_influxdb import sava_Opsdb
from charts.models import Host
from variable.models import System_variable
from libs.alarmspy.alarmtype1 import alarm_mysql
from utils.files_handle import get_linux_result


def set_redis():
    host_all = Host.objects.filter(host_status=0, is_manage=0).values('host_ip', 'host_name')
    variable_all = System_variable.objects.filter(var_group=1).values('var_lable', 'var_name', 'var_value')
    cache.set('host_all', list(host_all))

    variable_dit = {i['var_name']: i for i in variable_all}
    cache.set('variable_all', variable_dit)
    return host_all, variable_dit


def format_list(lit, host):
    '''
    格式化 ssh 返回的数据
    :param lit:
    :return: {'time': '2023-03-17 17:01:27', 'cpu%': 0.0, 'memory%': 24.8, 'disk%': 12.3, 'recvMB': 15, 'sentMB': 7, 'ip': '172.20.60.145'}
    '''
    dit = eval(lit)
    dit.update(host)
    return dit


# @app.task
# def sava_influxdb():
#     '''
#     将服务器返回的数据信息存入 influxdb 中
#     :return: 指点类型
#     '''
#     if not cache.get('host_all'):
#         host_all, variable_dit = set_redis()
#     else:
#         host_all = cache.get('host_all')
#         variable_dit = cache.get('variable_all')
#
#     for host in host_all:
#         # ip = '139.224.252.227'
#         ssh, sftp = do_ssh(host.get('host_ip'))
#         stdin, stdout, stderr = ssh.exec_command('python3 /ysg/p.py')
#         # 获取 脚本执行结果，并实例化数据
#         stdout_list = stdout.read().decode()
#         ret_dit = format_list(stdout_list, host)
#         # 与阀值比较，不同则录入报警信息到 MySQL 中
#         alarm_mysql(ret_dit, variable_dit)
#         # 入库到 influxdb【与比较结果无关】
#         sava_Opsdb(ret_dit)
#         ssh.close()  # 关闭连接
#
#
# @app.task
# def get_host():
#     set_redis()


@app.task
def fork_files(ip, localpath, textarea, filepath, ver_name):
    ssh, sftp = do_ssh(ip)
    sftp.put(localpath, '/ysg/back_up/back.zip')
    get_linux_result(ssh, f'rm -fr /ysg/back_up/back/')
    get_linux_result(ssh, f'unzip /ysg/back_up/back.zip -d /ysg/back_up/back/')
    textarea += ip + '\n' + f'python3 /ysg/monitorpy/systempy/update_zip.py {filepath} {ver_name}' + '\n'
    result = get_linux_result(ssh, f'python3 /ysg/monitorpy/systempy/update_zip.py {filepath} {ver_name}')
    textarea += ip + '\n' + result + '\n' + '\n'
    return textarea
